package com.atmilan.quartz.utils.source;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.atmilan.quartz.constant.enums.BarCodeEnum;
import com.atmilan.quartz.constant.enums.CategoryTypeEnum;
import com.atmilan.quartz.constant.enums.ProductTypeEnum;
import com.atmilan.quartz.constant.enums.StockAreaTempEnum;
import com.atmilan.quartz.model.dto.crmeb.StoreProductCrmebRequest;
import com.atmilan.quartz.model.entity.buyer.Supplier;
import com.atmilan.quartz.model.entity.crmeb.CategoryMatch;
import com.atmilan.quartz.model.entity.crmeb.StoreBrand;
import com.atmilan.quartz.model.entity.crmeb.StoreProductAttr;
import com.atmilan.quartz.model.entity.lavita.LavitaProduct;
import com.atmilan.quartz.model.entity.lavita.LavitaProductSku;
import com.atmilan.quartz.service.ICategoryMatchService;
import com.atmilan.quartz.service.IStoreBrandService;
import com.atmilan.quartz.service.ISupplierService;
import com.atmilan.quartz.sync.push.crmeb.domain.StoreProductAttrValueRequest;
import com.atmilan.quartz.sync.push.crmeb.enums.CrmebMerchantEnums;
import com.atmilan.quartz.utils.PriceUtil;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.pagehelper.util.StringUtil;

/**
 * 处理源数据转换和计算相关信息
 * @Description: 
 * @author daigb
 * @date 2021-03-05
 */
@Service
public class SourceLavitaProductUtil {
    @Autowired
    IStoreBrandService storeBrandService;
    @Autowired
    ICategoryMatchService categoryMatchService;
    @Autowired
    ISupplierService supplierService;
    @Autowired
    PriceUtil priceUtil;

    /**
     * 构建DO对象
     * @Description:
     * @author songjc
     * @param @param product
     * @param @param productSkus
     * @param @return
     * @return StoreProductRequest
     * @throws
     */
    public StoreProductCrmebRequest buildLavitaProduct(LavitaProduct product, List<LavitaProductSku> productSkus) {
        // 主商品对象
        StoreProductCrmebRequest productRequest = null;
        try {
            // 轮播图
            JSONArray gallery = new JSONArray();
            JSONArray galleryList = StringUtil.isEmpty(product.getImgList())  ? new JSONArray() : JSONArray.parseArray(product.getImgList());
            if (galleryList.size()!=0){
                List<JSONObject> jsonObjects = galleryList.toJavaList(JSONObject.class);
                jsonObjects.stream().forEach(e->{
                    String imgUrl = e.getString("imgUrl");
                    gallery.add(imgUrl);
                });
            }

            // 主图
            String mainImage = gallery.size()==0?"":gallery.get(0).toString();
            // 售价
            BigDecimal price = PriceUtil.hk2Rmb(product.getPrice());
            // 原价
            BigDecimal otPrice = BigDecimal.ZERO;//PriceUtil.rmb2Eur(PriceUtil.hk2Rmb(product.getBrandPrice()));
            // 品牌对应
            StoreBrand buyerStoreBrand = storeBrandService.getOne(Wrappers.<StoreBrand>lambdaQuery()
                    .eq(StoreBrand :: getEnName, product.getBrand())
                    .eq(StoreBrand :: getType, ProductTypeEnum.LAVITA)
                    .last("LIMIT 1")
            );
            storeBrandService.unMatchBrand(buyerStoreBrand,null,product.getBrand(),ProductTypeEnum.LAVITA);
            StoreBrand storeBrand = null;
            if(null != buyerStoreBrand) {
                if(null != buyerStoreBrand.getSuperId()) {
                    storeBrand = storeBrandService.getById(buyerStoreBrand.getSuperId());
                } else {
                    storeBrand = storeBrandService.getById(5429);
                }
            } else {
                storeBrand = storeBrandService.getById(5429);
            }

            /***** 处理对象构建 *******/
            String barCode = BarCodeEnum.LAVITA.getCode().toString() + product.getKuanId();
            List<StoreProductAttr> attrList = new ArrayList<StoreProductAttr>();
            List<StoreProductAttrValueRequest> attrValueList = new ArrayList<StoreProductAttrValueRequest>();
            // 规格
            StoreProductAttr storeProductAttr = new StoreProductAttr();
            storeProductAttr.setAttrName("尺寸");
            storeProductAttr.setType(0);
            storeProductAttr.setBarCode(barCode);
            // 颜色
            StoreProductAttr storeProductAttrColor = new StoreProductAttr();
            storeProductAttrColor.setAttrName("颜色");
            storeProductAttrColor.setType(0);
            storeProductAttrColor.setBarCode(barCode);
            // 合并成suk
            List<String> colorValueList = new ArrayList<String>();
            List<String> valueList = new ArrayList<String>();
            for(LavitaProductSku sku : productSkus) {
                // value对象
                StoreProductAttrValueRequest storeProductAttrValue = new StoreProductAttrValueRequest();
                storeProductAttrValue.setSourceSkuId(sku.getProductId());

                LinkedHashMap<String, String> linkedMap = new LinkedHashMap<>();
                List<String> suk = new ArrayList<String>();
                linkedMap.put("颜色", sku.getColor());
                if (!colorValueList.contains(sku.getColor())) {
                    colorValueList.add(sku.getColor());
                }
                suk.add(sku.getColor());
                linkedMap.put("尺寸", sku.getSize());
                if (!valueList.contains(sku.getSize())) {
                    valueList.add(sku.getSize());
                }
                suk.add(sku.getSize());
                storeProductAttrValue.setSuk(String.join(",", suk));
                storeProductAttrValue.setSkuCode(sku.getSkuCode());
                storeProductAttrValue.setSourcePrice(product.getPrice().toString());
                storeProductAttrValue.setAttrValue(linkedMap);
                storeProductAttrValue.setStock(sku.getQtyAvail());
                storeProductAttrValue.setPrice(price);
                storeProductAttrValue.setImage(mainImage);
                storeProductAttrValue.setCost(price);
                storeProductAttrValue.setSourceCost(price);
                storeProductAttrValue.setBarCode(barCode);
                storeProductAttrValue.setOtPrice(otPrice);
                storeProductAttrValue.setTempId(StockAreaTempEnum.HK.getTempId());
                attrValueList.add(storeProductAttrValue);
            }
            // attr对象
            if (CollectionUtils.isNotEmpty(colorValueList)) {
                storeProductAttrColor.setAttrValues(String.join(",", colorValueList));
                attrList.add(storeProductAttrColor);
            }
            if (CollectionUtils.isNotEmpty(valueList)) {
                storeProductAttr.setAttrValues(String.join(",", valueList));
                attrList.add(storeProductAttr);
            }

            productRequest = new StoreProductCrmebRequest();
            productRequest.setAttr(attrList);
            productRequest.setAttrValue(attrValueList);
            // 强制写一个 商户id 作为buyer商品标识标识
            productRequest.setMerId(CrmebMerchantEnums.LAVITA.getMerchantId());
            productRequest.setContent(product.getProductName());
            productRequest.setKeyword(product.getKuan());
            productRequest.setStoreInfo(product.getProductName());
            productRequest.setStoreName(product.getProductName());
            productRequest.setColorCode(product.getColorCode());
            productRequest.setSeasonCode(product.getSeasonCode());
            productRequest.setComposition(product.getComposition());
            if(null != storeBrand) {
                productRequest.setBrandId(storeBrand.getId());
                productRequest.setBrandName(storeBrand.getEnName());
            }
            productRequest.setPrice(price);
            productRequest.setOtPrice(otPrice);
            productRequest.setCost(price);
            productRequest.setSourceCost(price);
            productRequest.setPromoteFlag(false);
            productRequest.setErpPromFlag(true);
            productRequest.setTempId(StockAreaTempEnum.HK.getTempId());

            // 供应商
            Supplier supplier = supplierService.getOne(Wrappers.<Supplier>lambdaQuery()
                    .eq(Supplier :: getBarcode, BarCodeEnum.LAVITA.getCode())
                    .last("LIMIT 1")
            );
            if(null != supplier) {
                productRequest.setSuppliersId(supplier.getId());
                productRequest.setSuppliersName(supplier.getSuppliersName());
            }
            productRequest.setBarCode(barCode);
            // 分类
            CategoryMatch categoryMatch = categoryMatchService.getOne(Wrappers.<CategoryMatch>lambdaQuery()
                    .eq(CategoryMatch :: getType, CategoryTypeEnum.LAVITA)
                    .eq(CategoryMatch :: getOthCategoryId, product.getGender())
                    .eq(CategoryMatch :: getOthCategoryName, product.getCategoryName1())
                    .eq(CategoryMatch :: getOthCategoryType, product.getCategoryName2())
                    .last("LIMIT 1")
            );
            categoryMatchService.unMatchCategory(categoryMatch,product.getGender(),product.getCategoryName1(),product.getCategoryName2(),CategoryTypeEnum.LAVITA);
            // 复制重量
            if(null != categoryMatch) {
            	CategoryMatch supCategoryMatch = categoryMatchService.getById(categoryMatch.getCategoryId());
            	categoryMatch.setWeight(Optional.ofNullable(supCategoryMatch).orElse(new CategoryMatch()).getWeight());
            }
            Integer categoryId = null != categoryMatch ? categoryMatch.getCategoryId() : 1859;
            productRequest.setCateId(categoryId);
            productRequest.setCateIds(Arrays.asList(categoryId));
            productRequest.setWeight(null != categoryMatch ? categoryMatch.getWeight() : BigDecimal.ONE);
            productRequest.setImage(mainImage);
            if(gallery.size() > 0) {
                productRequest.setSliderImage(JSON.toJSONString(gallery));
            }
            productRequest.setIsShow(true);
            productRequest.setSpecType(true);
            productRequest.setIsEurope(ProductTypeEnum.LAVITA.getCode());
            productRequest.setUnitName("件");
            productRequest.setLastPushTime(new Date());
            productRequest.setAddTime(Integer.parseInt(String.valueOf(System.currentTimeMillis() / 1000L)));
            productRequest.setSeasonCode(product.getSeasonCode());
        } catch (Exception e) {
            e.printStackTrace();
        }

        return productRequest;
    }

}
